package com.leetcode.algorithm.y22.m08.w4;

import java.util.HashMap;
import java.util.Map;

/**
 * 904. 水果成篮
 * 
 * https://leetcode.cn/problems/fruit-into-baskets/
 * 
 * @author jie.deng
 *
 */
class Question0904Solution01 {

	public int totalFruit(int[] fruits) {
		int len = fruits.length;
		Map<Integer, Integer> map = new HashMap<>(3);
		int maxTotalFruit = 0;
		int left = 0;
		for (int right = 0; right < len; right++) {
			Integer cnt = map.get(fruits[right]);
			if (cnt == null) {
				map.put(fruits[right], 1);
			} else {
				map.put(fruits[right], cnt.intValue() + 1);
			}
			while (map.size() > 2) {
				int cntL = map.get(fruits[left]).intValue();
				if (cntL == 1) {
					map.remove(fruits[left]);
				} else {
					map.put(fruits[left], cntL - 1);
				}
				left++;
			}
			maxTotalFruit = Math.max(right - left + 1, maxTotalFruit);
		}

		return maxTotalFruit;
	}

}